import Vue from 'vue'
import { DEL_QUESTION } from '@/store/mutations'
import { AppInfo } from '@/lib/appMethods'

export default Vue.extend({
  props: {
    question: {
      type: Object,
      default: () => ({}),
    },
    index: {
      type: Number,
      default: 0,
    },
    qlength: {
      type: Number,
      default: 0,
    },
  },
  data () {
    return {
      collectState: {} as any,
      collectingState: {} as any,
      removingState: {} as any,
    }
  },
  computed: {
    isCollected (): boolean {
      const { QuestionId, IsCollection } = this.question
      return this.collectState[QuestionId] ? this.collectState[QuestionId] === 1 : IsCollection
    },
  },
  methods: {
    toggleCollect () {
      const { QuestionId } = this.question
      if (this.collectingState[QuestionId]) {
        return
      }
      this.collectingState[QuestionId] = true
      this.$axios({
        url: `user/${this.isCollected ? 'CancelCollectQuestion' : 'CollectQuestion'}`,
        data: {
          ClassId: this.$route.query.ClassId,
          CourseId: this.$route.query.CourseId,
          QuestionId,
          // CollectType: this.isCollected ? 2 : 1,
        },
      }).then(() => {
        this.$set(this.$data.collectState, QuestionId, this.isCollected ? 2 : 1)
        this.$toast({
          message: `${this.isCollected ? '' : '移除'}收藏成功`,
          duration: 2000,
        })
      }).finally(() => {
        delete this.collectingState[QuestionId]
      })
    },
    onRemoveItem () {
      const index = this.index
      const { QuestionId } = this.question
      if (this.removingState[QuestionId]) {
        return
      }
      this.removingState[QuestionId] = true
      this.$axios({
        url: 'user/RemoveUserWrongQuestion',
        data: {
          ClassId: this.$route.query.ClassId,
          CourseId: this.$route.query.CourseId,
          QuestionIds: QuestionId,
        },
      }).then(() => {
        if (this.qlength === 1) {
          AppInfo.callMethod('goBack')
        } else {
          this.$emit('reload', index)
          this.$store.commit(DEL_QUESTION, index)
          this.$toast({
            message: '移除错题成功',
            duration: 2000,
          })
        }
      }).finally(() => {
        delete this.removingState[QuestionId]
      })
    },
  },
})
